var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors') //node解决跨域问题
var jwt = require('jsonwebtoken')  //引入token
var secret = 'asdfasdfasdfas46546asdfasdf654a6sdfa' //私钥

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const { createProxyMiddleware } = require('http-proxy-middleware');

var app = express();
require('./database/connect.js')  //引入数据库连接文件
app.use(cors())  //引入解决跨域问题文件
app.use('/hehe', createProxyMiddleware({  //服务代理
    target:'https://www.160dyf.com', //代理的目标服务器地址
    pathRewrite:{ //路径重写
        '^/hehe':''  //剔除代理路径
    },
    changeOrigin: true 
}));
app.use('/local', createProxyMiddleware({  //服务代理
    target:'http://localhost:3000', //代理的目标服务器地址
    pathRewrite:{ //路径重写
        '^/local':''  //剔除代理路径
    },
    changeOrigin: true 
}));
app.use('/node', createProxyMiddleware({  //服务代理
    target:'http://localhost:3000', //代理的目标服务器地址
    pathRewrite:{ //路径重写
        '^/node':''  //剔除代理路径
    },
    changeOrigin: true 
}));
app.use(logger('dev')); 
app.use(express.json()); 
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/stu',(req,res,next)=>{
    console.log('接口路由拦截',req.headers)
    let {token} = req.headers
    jwt.verify(token,secret,(err,decoded)=>{//err是token鉴权失败后的信息，decoded是token鉴权成功后的信息
        console.log(11,err,decoded)
        //验证token合法性
        if(err){
            res.send({
                code:103,
                msg:'非法token,请登录',
            })
            return 
        }
        //验证token有效性
        let {time,expire} = decoded
        let now = Date.now() //鉴权的当前时间
        if(now - time >= expire){ //判断token过期与否
            res.send({
                code:103,
                msg:'token已过期，请重新登录'
            })
        }
    })
    next() //鉴权成功，放行
}, indexRouter);
app.use('/users', usersRouter);

module.exports = app;
